import os
import sys
from SCons import Script
import awtk_locator as locator

def Helper(ARGUMENTS):
    locator.init(ARGUMENTS)
    from app_helper_base import AppHelperBase

    class AppHelper(AppHelperBase):
        def __init__(self, args):
            AppHelperBase.__init__(self, args)

        def SConscript(self, scripts):
            rets = []
            if not self.BUILD_DIR:
                rets += Script.SConscript(scripts)
            else:
                for script in scripts:
                    dir = os.path.dirname(script)
                    build_dir = os.path.join(self.BUILD_DIR, dir)
                    rets += Script.SConscript(script, variant_dir=build_dir, duplicate=False)
            return rets

        def get_sconscripts(self, dirs):
            scripts = []
            for dir in dirs:
                script = os.path.join(dir, 'SConscript')
                scripts.append(script)
            return scripts

        def Objects(self, srcs):
            objs = []
            for src in srcs:
                objs += Script.Object(src)
            return objs

    return AppHelper(ARGUMENTS)

def prepare_depends_libs(ARGUMENTS, helper, libs):
    if ARGUMENTS.get('PREPARE_DEPENDS', '').lower().startswith('f'):
        return

    args = ' AWTK_ROOT=' + helper.AWTK_ROOT
    if helper.MVVM_ROOT:
        args += ' MVVM_ROOT=' + helper.MVVM_ROOT

    for key in ARGUMENTS:
        if not key == 'AWTK_ROOT' and not key == 'MVVM_ROOT':
            args += ' ' + key + '=' + ARGUMENTS[key]

    num_jobs_str = ''
    num_jobs = Script.GetOption('num_jobs')
    if num_jobs > 1:
        num_jobs_str = ' -j' + str(num_jobs)

    clean_str = ''
    if Script.GetOption('clean'):
        clean_str = ' -c '

    for lib in libs:
        if 'root' in lib and os.path.exists(lib['root'] + '/SConstruct'):
            cmd = 'cd ' + lib['root'] + ' && scons' + clean_str + num_jobs_str + args
            print(cmd)
            result = os.system(cmd)
            if not result == 0:
                sys.exit(result)
